{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "copyright-notice"
   },
   "source": [
    "#### Copyright 2017 Google LLC."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "copyright-notice2"
   },
   "outputs": [],
   "source": [
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "g4T-_IsVbweU"
   },
   "source": [
    " # 特征组合"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "F7dke6skIK-k"
   },
   "source": [
    " **学习目标：**\n",
    "  * 通过添加其他合成特征来改进线性回归模型（这是前一个练习的延续）\n",
    "  * 使用输入函数将 Pandas `DataFrame` 对象转换为 `Tensors`，并在 `fit()` 和 `predict()` 中调用输入函数\n",
    "  * 使用 FTRL 优化算法进行模型训练\n",
    "  * 通过独热编码、分箱和特征组合创建新的合成特征"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NS_fcQRd8B97"
   },
   "source": [
    " ## 设置"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "4IdzD8IdIK-l"
   },
   "source": [
    " 首先，我们来定义输入并创建数据加载代码，正如我们在之前的练习中所做的那样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "CsfdiLiDIK-n"
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "\n",
    "import math\n",
    "\n",
    "from IPython import display\n",
    "from matplotlib import cm\n",
    "from matplotlib import gridspec\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn import metrics\n",
    "import tensorflow as tf\n",
    "from tensorflow.python.data import Dataset\n",
    "\n",
    "tf.logging.set_verbosity(tf.logging.ERROR)\n",
    "pd.options.display.max_rows = 10\n",
    "pd.options.display.float_format = '{:.1f}'.format\n",
    "\n",
    "california_housing_dataframe = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv\", sep=\",\")\n",
    "\n",
    "california_housing_dataframe = california_housing_dataframe.reindex(\n",
    "    np.random.permutation(california_housing_dataframe.index))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "10rhoflKIK-s"
   },
   "outputs": [],
   "source": [
    "def preprocess_features(california_housing_dataframe):\n",
    "  \"\"\"Prepares input features from California housing data set.\n",
    "\n",
    "  Args:\n",
    "    california_housing_dataframe: A Pandas DataFrame expected to contain data\n",
    "      from the California housing data set.\n",
    "  Returns:\n",
    "    A DataFrame that contains the features to be used for the model, including\n",
    "    synthetic features.\n",
    "  \"\"\"\n",
    "  selected_features = california_housing_dataframe[\n",
    "    [\"latitude\",\n",
    "     \"longitude\",\n",
    "     \"housing_median_age\",\n",
    "     \"total_rooms\",\n",
    "     \"total_bedrooms\",\n",
    "     \"population\",\n",
    "     \"households\",\n",
    "     \"median_income\"]]\n",
    "  processed_features = selected_features.copy()\n",
    "  # Create a synthetic feature.\n",
    "  processed_features[\"rooms_per_person\"] = (\n",
    "    california_housing_dataframe[\"total_rooms\"] /\n",
    "    california_housing_dataframe[\"population\"])\n",
    "  return processed_features\n",
    "\n",
    "def preprocess_targets(california_housing_dataframe):\n",
    "  \"\"\"Prepares target features (i.e., labels) from California housing data set.\n",
    "\n",
    "  Args:\n",
    "    california_housing_dataframe: A Pandas DataFrame expected to contain data\n",
    "      from the California housing data set.\n",
    "  Returns:\n",
    "    A DataFrame that contains the target feature.\n",
    "  \"\"\"\n",
    "  output_targets = pd.DataFrame()\n",
    "  # Scale the target to be in units of thousands of dollars.\n",
    "  output_targets[\"median_house_value\"] = (\n",
    "    california_housing_dataframe[\"median_house_value\"] / 1000.0)\n",
    "  return output_targets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "ufplEkjN8KUp"
   },
   "outputs": [],
   "source": [
    "# Choose the first 12000 (out of 17000) examples for training.\n",
    "training_examples = preprocess_features(california_housing_dataframe.head(12000))\n",
    "training_targets = preprocess_targets(california_housing_dataframe.head(12000))\n",
    "\n",
    "# Choose the last 5000 (out of 17000) examples for validation.\n",
    "validation_examples = preprocess_features(california_housing_dataframe.tail(5000))\n",
    "validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))\n",
    "\n",
    "# Double-check that we've done the right thing.\n",
    "print(\"Training examples summary:\")\n",
    "display.display(training_examples.describe())\n",
    "print(\"Validation examples summary:\")\n",
    "display.display(validation_examples.describe())\n",
    "\n",
    "print(\"Training targets summary:\")\n",
    "display.display(training_targets.describe())\n",
    "print(\"Validation targets summary:\")\n",
    "display.display(validation_targets.describe())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "oJlrB4rJ_2Ma"
   },
   "outputs": [],
   "source": [
    "def construct_feature_columns(input_features):\n",
    "  \"\"\"Construct the TensorFlow Feature Columns.\n",
    "\n",
    "  Args:\n",
    "    input_features: The names of the numerical input features to use.\n",
    "  Returns:\n",
    "    A set of feature columns\n",
    "  \"\"\"\n",
    "  return set([tf.feature_column.numeric_column(my_feature)\n",
    "              for my_feature in input_features])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "NBxoAfp2AcB6"
   },
   "outputs": [],
   "source": [
    "def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n",
    "    \"\"\"Trains a linear regression model.\n",
    "  \n",
    "    Args:\n",
    "      features: pandas DataFrame of features\n",
    "      targets: pandas DataFrame of targets\n",
    "      batch_size: Size of batches to be passed to the model\n",
    "      shuffle: True or False. Whether to shuffle the data.\n",
    "      num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n",
    "    Returns:\n",
    "      Tuple of (features, labels) for next data batch\n",
    "    \"\"\"\n",
    "    \n",
    "    # Convert pandas data into a dict of np arrays.\n",
    "    features = {key:np.array(value) for key,value in dict(features).items()}                                           \n",
    " \n",
    "    # Construct a dataset, and configure batching/repeating.\n",
    "    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n",
    "    ds = ds.batch(batch_size).repeat(num_epochs)\n",
    "    \n",
    "    # Shuffle the data, if specified.\n",
    "    if shuffle:\n",
    "      ds = ds.shuffle(10000)\n",
    "    \n",
    "    # Return the next batch of data.\n",
    "    features, labels = ds.make_one_shot_iterator().get_next()\n",
    "    return features, labels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "hweDyy31LBsV"
   },
   "source": [
    " ## FTRL 优化算法\n",
    "\n",
    "高维度线性模型可受益于使用一种基于梯度的优化方法，叫做 FTRL。该算法的优势是针对不同系数以不同方式调整学习速率，如果某些特征很少采用非零值，该算法可能比较实用（也非常适合支持 L1 正则化）。我们可以使用 [FtrlOptimizer](https://www.tensorflow.org/api_docs/python/tf/train/FtrlOptimizer) 来应用 FTRL。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "S0SBf1X1IK_O"
   },
   "outputs": [],
   "source": [
    "def train_model(\n",
    "    learning_rate,\n",
    "    steps,\n",
    "    batch_size,\n",
    "    feature_columns,\n",
    "    training_examples,\n",
    "    training_targets,\n",
    "    validation_examples,\n",
    "    validation_targets):\n",
    "  \"\"\"Trains a linear regression model.\n",
    "  \n",
    "  In addition to training, this function also prints training progress information,\n",
    "  as well as a plot of the training and validation loss over time.\n",
    "  \n",
    "  Args:\n",
    "    learning_rate: A `float`, the learning rate.\n",
    "    steps: A non-zero `int`, the total number of training steps. A training step\n",
    "      consists of a forward and backward pass using a single batch.\n",
    "    feature_columns: A `set` specifying the input feature columns to use.\n",
    "    training_examples: A `DataFrame` containing one or more columns from\n",
    "      `california_housing_dataframe` to use as input features for training.\n",
    "    training_targets: A `DataFrame` containing exactly one column from\n",
    "      `california_housing_dataframe` to use as target for training.\n",
    "    validation_examples: A `DataFrame` containing one or more columns from\n",
    "      `california_housing_dataframe` to use as input features for validation.\n",
    "    validation_targets: A `DataFrame` containing exactly one column from\n",
    "      `california_housing_dataframe` to use as target for validation.\n",
    "      \n",
    "  Returns:\n",
    "    A `LinearRegressor` object trained on the training data.\n",
    "  \"\"\"\n",
    "\n",
    "  periods = 10\n",
    "  steps_per_period = steps / periods\n",
    "\n",
    "  # Create a linear regressor object.\n",
    "  my_optimizer = tf.train.FtrlOptimizer(learning_rate=learning_rate)\n",
    "  my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n",
    "  linear_regressor = tf.estimator.LinearRegressor(\n",
    "      feature_columns=feature_columns,\n",
    "      optimizer=my_optimizer\n",
    "  )\n",
    "  \n",
    "  training_input_fn = lambda: my_input_fn(training_examples, \n",
    "                                          training_targets[\"median_house_value\"], \n",
    "                                          batch_size=batch_size)\n",
    "  predict_training_input_fn = lambda: my_input_fn(training_examples, \n",
    "                                                  training_targets[\"median_house_value\"], \n",
    "                                                  num_epochs=1, \n",
    "                                                  shuffle=False)\n",
    "  predict_validation_input_fn = lambda: my_input_fn(validation_examples, \n",
    "                                                    validation_targets[\"median_house_value\"], \n",
    "                                                    num_epochs=1, \n",
    "                                                    shuffle=False)\n",
    "\n",
    "  # Train the model, but do so inside a loop so that we can periodically assess\n",
    "  # loss metrics.\n",
    "  print(\"Training model...\")\n",
    "  print(\"RMSE (on training data):\")\n",
    "  training_rmse = []\n",
    "  validation_rmse = []\n",
    "  for period in range (0, periods):\n",
    "    # Train the model, starting from the prior state.\n",
    "    linear_regressor.train(\n",
    "        input_fn=training_input_fn,\n",
    "        steps=steps_per_period\n",
    "    )\n",
    "    # Take a break and compute predictions.\n",
    "    training_predictions = linear_regressor.predict(input_fn=predict_training_input_fn)\n",
    "    training_predictions = np.array([item['predictions'][0] for item in training_predictions])\n",
    "    validation_predictions = linear_regressor.predict(input_fn=predict_validation_input_fn)\n",
    "    validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])\n",
    "    \n",
    "    # Compute training and validation loss.\n",
    "    training_root_mean_squared_error = math.sqrt(\n",
    "        metrics.mean_squared_error(training_predictions, training_targets))\n",
    "    validation_root_mean_squared_error = math.sqrt(\n",
    "        metrics.mean_squared_error(validation_predictions, validation_targets))\n",
    "    # Occasionally print the current loss.\n",
    "    print(\"  period %02d : %0.2f\" % (period, training_root_mean_squared_error))\n",
    "    # Add the loss metrics from this period to our list.\n",
    "    training_rmse.append(training_root_mean_squared_error)\n",
    "    validation_rmse.append(validation_root_mean_squared_error)\n",
    "  print(\"Model training finished.\")\n",
    "\n",
    "  \n",
    "  # Output a graph of loss metrics over periods.\n",
    "  plt.ylabel(\"RMSE\")\n",
    "  plt.xlabel(\"Periods\")\n",
    "  plt.title(\"Root Mean Squared Error vs. Periods\")\n",
    "  plt.tight_layout()\n",
    "  plt.plot(training_rmse, label=\"training\")\n",
    "  plt.plot(validation_rmse, label=\"validation\")\n",
    "  plt.legend()\n",
    "\n",
    "  return linear_regressor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "1Cdr02tLIK_Q"
   },
   "outputs": [],
   "source": [
    "_ = train_model(\n",
    "    learning_rate=1.0,\n",
    "    steps=500,\n",
    "    batch_size=100,\n",
    "    feature_columns=construct_feature_columns(training_examples),\n",
    "    training_examples=training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "i4lGvqajDWlw"
   },
   "source": [
    " ## 离散特征的独热编码\n",
    "\n",
    "通常，在训练逻辑回归模型之前，离散（即字符串、枚举、整数）特征会转换为二元特征系列。\n",
    "\n",
    "例如，假设我们创建了一个合成特征，可以采用 `0`、`1` 或 `2` 中的任何值，并且我们还具有以下几个训练点：\n",
    "\n",
    "| # | feature_value |\n",
    "|---|---------------|\n",
    "| 0 |             2 |\n",
    "| 1 |             0 |\n",
    "| 2 |             1 |\n",
    "\n",
    "对于每个可能的分类值，我们都会创建一个新的**二元****实值**特征，该特征只能采用两个可能值中的一个：如果示例中包含该值，则值为 1.0；如果不包含，则值为 0.0。在上述示例中，分类特征会被转换成三个特征，现在训练点如下所示：\n",
    "\n",
    "| # | feature_value_0 | feature_value_1 | feature_value_2 |\n",
    "|---|-----------------|-----------------|-----------------|\n",
    "| 0 |             0.0 |             0.0 |             1.0 |\n",
    "| 1 |             1.0 |             0.0 |             0.0 |\n",
    "| 2 |             0.0 |             1.0 |             0.0 |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KnssXowblKm7"
   },
   "source": [
    " ## 分桶（分箱）特征\n",
    "\n",
    "分桶也称为分箱。\n",
    "\n",
    "例如，我们可以将 `population` 分为以下 3 个分桶：\n",
    "- `bucket_0` (`< 5000`)：对应于人口分布较少的街区\n",
    "- `bucket_1` (`5000 - 25000`)：对应于人口分布适中的街区\n",
    "- `bucket_2` (`> 25000`)：对应于人口分布较多的街区\n",
    "\n",
    "根据前面的分桶定义，以下 `population` 矢量：\n",
    "\n",
    "    [[10001], [42004], [2500], [18000]]\n",
    "\n",
    "将变成以下经过分桶的特征矢量：\n",
    "\n",
    "    [[1], [2], [0], [1]]\n",
    "\n",
    "这些特征值现在是分桶索引。请注意，这些索引被视为离散特征。通常情况下，这些特征将被进一步转换为上述独热表示法，但这是以透明方式实现的。\n",
    "\n",
    "要为分桶特征定义特征列，我们可以使用 [`bucketized_column`](https://www.tensorflow.org/api_docs/python/tf/feature_column/bucketized_column)（而不是使用 `numeric_column`），该列将数字列作为输入，并使用 `boundardies` 参数中指定的分桶边界将其转换为分桶特征。以下代码为 `households` 和 `longitude` 定义了分桶特征列；`get_quantile_based_boundaries` 函数会根据分位数计算边界，以便每个分桶包含相同数量的元素。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "cc9qZrtRy-ED"
   },
   "outputs": [],
   "source": [
    "def get_quantile_based_boundaries(feature_values, num_buckets):\n",
    "  boundaries = np.arange(1.0, num_buckets) / num_buckets\n",
    "  quantiles = feature_values.quantile(boundaries)\n",
    "  return [quantiles[q] for q in quantiles.keys()]\n",
    "\n",
    "# Divide households into 7 buckets.\n",
    "households = tf.feature_column.numeric_column(\"households\")\n",
    "bucketized_households = tf.feature_column.bucketized_column(\n",
    "  households, boundaries=get_quantile_based_boundaries(\n",
    "    california_housing_dataframe[\"households\"], 7))\n",
    "\n",
    "# Divide longitude into 10 buckets.\n",
    "longitude = tf.feature_column.numeric_column(\"longitude\")\n",
    "bucketized_longitude = tf.feature_column.bucketized_column(\n",
    "  longitude, boundaries=get_quantile_based_boundaries(\n",
    "    california_housing_dataframe[\"longitude\"], 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "U-pQDAa0MeN3"
   },
   "source": [
    " ## 任务 1：使用分桶特征列训练模型\n",
    "**将我们示例中的所有实值特征进行分桶，训练模型，然后查看结果是否有所改善。**\n",
    "\n",
    "在前面的代码块中，两个实值列（即 `households` 和 `longitude`）已被转换为分桶特征列。您的任务是对其余的列进行分桶，然后运行代码来训练模型。您可以采用各种启发法来确定分桶的范围。本练习使用了分位数技巧，通过这种方式选择分桶边界后，每个分桶将包含相同数量的样本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "YFXV9lyMLedy"
   },
   "outputs": [],
   "source": [
    "def construct_feature_columns():\n",
    "  \"\"\"Construct the TensorFlow Feature Columns.\n",
    "\n",
    "  Returns:\n",
    "    A set of feature columns\n",
    "  \"\"\" \n",
    "  households = tf.feature_column.numeric_column(\"households\")\n",
    "  longitude = tf.feature_column.numeric_column(\"longitude\")\n",
    "  latitude = tf.feature_column.numeric_column(\"latitude\")\n",
    "  housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n",
    "  median_income = tf.feature_column.numeric_column(\"median_income\")\n",
    "  rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n",
    "  \n",
    "  # Divide households into 7 buckets.\n",
    "  bucketized_households = tf.feature_column.bucketized_column(\n",
    "    households, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"households\"], 7))\n",
    "\n",
    "  # Divide longitude into 10 buckets.\n",
    "  bucketized_longitude = tf.feature_column.bucketized_column(\n",
    "    longitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"longitude\"], 10))\n",
    "\n",
    "  #\n",
    "  # YOUR CODE HERE: bucketize the following columns, following the example above:\n",
    "  #\n",
    "  bucketized_latitude = \n",
    "  bucketized_housing_median_age = \n",
    "  bucketized_median_income =\n",
    "  bucketized_rooms_per_person =\n",
    "  \n",
    "  feature_columns = set([\n",
    "    bucketized_longitude,\n",
    "    bucketized_latitude,\n",
    "    bucketized_housing_median_age,\n",
    "    bucketized_households,\n",
    "    bucketized_median_income,\n",
    "    bucketized_rooms_per_person])\n",
    "  \n",
    "  return feature_columns\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "0FfUytOTNJhL"
   },
   "outputs": [],
   "source": [
    "_ = train_model(\n",
    "    learning_rate=1.0,\n",
    "    steps=500,\n",
    "    batch_size=100,\n",
    "    feature_columns=construct_feature_columns(),\n",
    "    training_examples=training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZTDHHM61NPTw"
   },
   "source": [
    " ### 解决方案\n",
    "\n",
    "点击下方即可查看解决方案。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "JQHnUhL_NRwA"
   },
   "source": [
    " 您可能想知道如何确定要使用多少个分桶。这当然要取决于数据。在这里，我们只是选择了任意值，以获得一个不太大的模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "Ro5civQ3Ngh_"
   },
   "outputs": [],
   "source": [
    "def construct_feature_columns():\n",
    "  \"\"\"Construct the TensorFlow Feature Columns.\n",
    "\n",
    "  Returns:\n",
    "    A set of feature columns\n",
    "  \"\"\" \n",
    "  households = tf.feature_column.numeric_column(\"households\")\n",
    "  longitude = tf.feature_column.numeric_column(\"longitude\")\n",
    "  latitude = tf.feature_column.numeric_column(\"latitude\")\n",
    "  housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n",
    "  median_income = tf.feature_column.numeric_column(\"median_income\")\n",
    "  rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n",
    "  \n",
    "  # Divide households into 7 buckets.\n",
    "  bucketized_households = tf.feature_column.bucketized_column(\n",
    "    households, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"households\"], 7))\n",
    "\n",
    "  # Divide longitude into 10 buckets.\n",
    "  bucketized_longitude = tf.feature_column.bucketized_column(\n",
    "    longitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"longitude\"], 10))\n",
    "  \n",
    "  # Divide latitude into 10 buckets.\n",
    "  bucketized_latitude = tf.feature_column.bucketized_column(\n",
    "    latitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"latitude\"], 10))\n",
    "\n",
    "  # Divide housing_median_age into 7 buckets.\n",
    "  bucketized_housing_median_age = tf.feature_column.bucketized_column(\n",
    "    housing_median_age, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"housing_median_age\"], 7))\n",
    "  \n",
    "  # Divide median_income into 7 buckets.\n",
    "  bucketized_median_income = tf.feature_column.bucketized_column(\n",
    "    median_income, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"median_income\"], 7))\n",
    "  \n",
    "  # Divide rooms_per_person into 7 buckets.\n",
    "  bucketized_rooms_per_person = tf.feature_column.bucketized_column(\n",
    "    rooms_per_person, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"rooms_per_person\"], 7))\n",
    "  \n",
    "  feature_columns = set([\n",
    "    bucketized_longitude,\n",
    "    bucketized_latitude,\n",
    "    bucketized_housing_median_age,\n",
    "    bucketized_households,\n",
    "    bucketized_median_income,\n",
    "    bucketized_rooms_per_person])\n",
    "  \n",
    "  return feature_columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "RNgfYk6OO8Sy"
   },
   "outputs": [],
   "source": [
    "_ = train_model(\n",
    "    learning_rate=1.0,\n",
    "    steps=500,\n",
    "    batch_size=100,\n",
    "    feature_columns=construct_feature_columns(),\n",
    "    training_examples=training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "AFJ1qoZPlQcs"
   },
   "source": [
    " ## 特征组合\n",
    "\n",
    "组合两个（或更多个）特征是使用线性模型来学习非线性关系的一种聪明做法。在我们的问题中，如果我们只使用 `latitude` 特征进行学习，那么该模型可能会发现特定纬度（或特定纬度范围内，因为我们已经将其分桶）的城市街区更可能比其他街区住房成本高昂。`longitude` 特征的情况与此类似。但是，如果我们将 `longitude` 与 `latitude` 组合，产生的组合特征则代表一个明确的城市街区。如果模型发现某些城市街区（位于特定纬度和经度范围内）更可能比其他街区住房成本高昂，那么这将是比单独考虑两个特征更强烈的信号。\n",
    "\n",
    "目前，特征列 API 仅支持组合离散特征。要组合两个连续的值（比如 `latitude` 或 `longitude`），我们可以对其进行分桶。\n",
    "\n",
    "如果我们组合 `latitude` 和 `longitude` 特征（例如，假设 `longitude` 被分到 `2` 个分桶中，而 `latitude` 有 `3` 个分桶），我们实际上会得到 6 个组合的二元特征。当我们训练模型时，每个特征都会分别获得自己的权重。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-Rk0c1oTYaVH"
   },
   "source": [
    " ## 任务 2：使用特征组合训练模型\n",
    "\n",
    "**在模型中添加 `longitude` 与 `latitude` 的特征组合，训练模型，然后确定结果是否有所改善。**\n",
    "\n",
    "请参阅有关 [`crossed_column()`](https://www.tensorflow.org/api_docs/python/tf/feature_column/crossed_column) 的 TensorFlow API 文档，了解如何为您的组合构建特征列。`hash_bucket_size` 可以设为 `1000`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "-eYiVEGeYhUi"
   },
   "outputs": [],
   "source": [
    "def construct_feature_columns():\n",
    "  \"\"\"Construct the TensorFlow Feature Columns.\n",
    "\n",
    "  Returns:\n",
    "    A set of feature columns\n",
    "  \"\"\" \n",
    "  households = tf.feature_column.numeric_column(\"households\")\n",
    "  longitude = tf.feature_column.numeric_column(\"longitude\")\n",
    "  latitude = tf.feature_column.numeric_column(\"latitude\")\n",
    "  housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n",
    "  median_income = tf.feature_column.numeric_column(\"median_income\")\n",
    "  rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n",
    "  \n",
    "  # Divide households into 7 buckets.\n",
    "  bucketized_households = tf.feature_column.bucketized_column(\n",
    "    households, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"households\"], 7))\n",
    "\n",
    "  # Divide longitude into 10 buckets.\n",
    "  bucketized_longitude = tf.feature_column.bucketized_column(\n",
    "    longitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"longitude\"], 10))\n",
    "  \n",
    "  # Divide latitude into 10 buckets.\n",
    "  bucketized_latitude = tf.feature_column.bucketized_column(\n",
    "    latitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"latitude\"], 10))\n",
    "\n",
    "  # Divide housing_median_age into 7 buckets.\n",
    "  bucketized_housing_median_age = tf.feature_column.bucketized_column(\n",
    "    housing_median_age, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"housing_median_age\"], 7))\n",
    "  \n",
    "  # Divide median_income into 7 buckets.\n",
    "  bucketized_median_income = tf.feature_column.bucketized_column(\n",
    "    median_income, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"median_income\"], 7))\n",
    "  \n",
    "  # Divide rooms_per_person into 7 buckets.\n",
    "  bucketized_rooms_per_person = tf.feature_column.bucketized_column(\n",
    "    rooms_per_person, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"rooms_per_person\"], 7))\n",
    "  \n",
    "  # YOUR CODE HERE: Make a feature column for the long_x_lat feature cross\n",
    "  long_x_lat = \n",
    "  \n",
    "  feature_columns = set([\n",
    "    bucketized_longitude,\n",
    "    bucketized_latitude,\n",
    "    bucketized_housing_median_age,\n",
    "    bucketized_households,\n",
    "    bucketized_median_income,\n",
    "    bucketized_rooms_per_person,\n",
    "    long_x_lat])\n",
    "  \n",
    "  return feature_columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "xZuZMp3EShkM"
   },
   "outputs": [],
   "source": [
    "_ = train_model(\n",
    "    learning_rate=1.0,\n",
    "    steps=500,\n",
    "    batch_size=100,\n",
    "    feature_columns=construct_feature_columns(),\n",
    "    training_examples=training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "0i7vGo9PTaZl"
   },
   "source": [
    " ### 解决方案\n",
    "\n",
    "点击下方即可查看解决方案。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "3tAWu8qSTe2v"
   },
   "outputs": [],
   "source": [
    "def construct_feature_columns():\n",
    "  \"\"\"Construct the TensorFlow Feature Columns.\n",
    "\n",
    "  Returns:\n",
    "    A set of feature columns\n",
    "  \"\"\" \n",
    "  households = tf.feature_column.numeric_column(\"households\")\n",
    "  longitude = tf.feature_column.numeric_column(\"longitude\")\n",
    "  latitude = tf.feature_column.numeric_column(\"latitude\")\n",
    "  housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n",
    "  median_income = tf.feature_column.numeric_column(\"median_income\")\n",
    "  rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n",
    "  \n",
    "  # Divide households into 7 buckets.\n",
    "  bucketized_households = tf.feature_column.bucketized_column(\n",
    "    households, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"households\"], 7))\n",
    "\n",
    "  # Divide longitude into 10 buckets.\n",
    "  bucketized_longitude = tf.feature_column.bucketized_column(\n",
    "    longitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"longitude\"], 10))\n",
    "  \n",
    "  # Divide latitude into 10 buckets.\n",
    "  bucketized_latitude = tf.feature_column.bucketized_column(\n",
    "    latitude, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"latitude\"], 10))\n",
    "\n",
    "  # Divide housing_median_age into 7 buckets.\n",
    "  bucketized_housing_median_age = tf.feature_column.bucketized_column(\n",
    "    housing_median_age, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"housing_median_age\"], 7))\n",
    "  \n",
    "  # Divide median_income into 7 buckets.\n",
    "  bucketized_median_income = tf.feature_column.bucketized_column(\n",
    "    median_income, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"median_income\"], 7))\n",
    "  \n",
    "  # Divide rooms_per_person into 7 buckets.\n",
    "  bucketized_rooms_per_person = tf.feature_column.bucketized_column(\n",
    "    rooms_per_person, boundaries=get_quantile_based_boundaries(\n",
    "      training_examples[\"rooms_per_person\"], 7))\n",
    "  \n",
    "  # YOUR CODE HERE: Make a feature column for the long_x_lat feature cross\n",
    "  long_x_lat = tf.feature_column.crossed_column(\n",
    "  set([bucketized_longitude, bucketized_latitude]), hash_bucket_size=1000) \n",
    "  \n",
    "  feature_columns = set([\n",
    "    bucketized_longitude,\n",
    "    bucketized_latitude,\n",
    "    bucketized_housing_median_age,\n",
    "    bucketized_households,\n",
    "    bucketized_median_income,\n",
    "    bucketized_rooms_per_person,\n",
    "    long_x_lat])\n",
    "  \n",
    "  return feature_columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "-_vvNYIyTtPC"
   },
   "outputs": [],
   "source": [
    "_ = train_model(\n",
    "    learning_rate=1.0,\n",
    "    steps=500,\n",
    "    batch_size=100,\n",
    "    feature_columns=construct_feature_columns(),\n",
    "    training_examples=training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ymlHJ-vrhLZw"
   },
   "source": [
    " ## 可选挑战：尝试更多合成特征\n",
    "\n",
    "到目前为止，我们已经尝试了简单的分桶列和特征组合，但还有更多组合有可能会改进结果。例如，您可以组合多个列。如果改变分桶的数量，会出现什么情况？您还能想到哪些其他的合成特征？它们能否改进模型效果？"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "ZTDHHM61NPTw",
    "0i7vGo9PTaZl",
    "copyright-notice"
   ],
   "default_view": {},
   "name": "feature_crosses.ipynb",
   "provenance": [],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
